package com.example.cdctravel

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.cdctravel.R
import com.example.cdctravel.DataBaseHelper.Companion.getInstance

class Regiter : AppCompatActivity() {
    private var name: EditText? = null
    private var password: EditText? = null
    private var queren: Button? = null
    private var quxiao: Button? = null
    private var dbHelper: DataBaseHelper? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.regiter)
        dbHelper = getInstance(this)
        iniview()
        quxiao!!.setOnClickListener { finish() }
        queren!!.setOnClickListener {
            val Name = name!!.text.toString()
            val Password = password!!.text.toString()
            val db = dbHelper!!.writableDatabase
            if (Name == "") {
                Toast.makeText(this@Regiter, "账号不能为空", Toast.LENGTH_SHORT).show()
            } else {
                if (Password == "") {
                    Toast.makeText(this@Regiter, "密码不能为空", Toast.LENGTH_SHORT).show()
                } else {
                    val cursor = db.rawQuery("select name from users where name=? ", arrayOf(Name))
                    //用户是否存在
                    if (cursor.moveToNext()) {
                        Toast.makeText(this@Regiter, "该用户已经存在", Toast.LENGTH_SHORT).show()
                        cursor.close()
                    } else {
                        db.execSQL(
                            "insert into users(name,password)values(?,?)",
                            arrayOf(Name, Password)
                        )
                        Toast.makeText(this@Regiter, "注册成功", Toast.LENGTH_SHORT).show()
                        cursor.close()
                        finish()
                    }
                }
            }
        }
    }

    private fun iniview() {
        name = findViewById(R.id.zhanghao)
        password = findViewById(R.id.mima)
        queren = findViewById(R.id.queding)
        quxiao = findViewById(R.id.quxiao)
    }
}